<template>
  <section class="wh-full">
    <header class="flex-b plr-16px h-64px bg-#fff rd-4px">
      <a-form ref="searchRormRef" :model="searchFormState" name="searchForm" layout="inline" autocomplete="off" @finish="onFinishSearch">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="searchFormState.name"> </a-input>
        </a-form-item>
        <a-form-item label="编码" name="code">
          <a-input v-model:value="searchFormState.code"> </a-input>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button :disabled="disabledSeachBtn" type="primary" html-type="submit">搜索</a-button>
            <a-button key="reset" @click="resetSearchForm">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </header>
    <section class="main-box bg-#fff rd-4px plr-16px">
      <div class="h-52px flex-b">
        <div class="text-18px font-bold">角色列表</div>
        <div>
          <a-space>
            <a-button type="primary" size="middle" @click.stop="showModal('新增角色', CURDTYPE.新增)">新增角色</a-button>
          </a-space>
        </div>
      </div>
      <div class="main-content" ref="mainContentRef">
        <a-table
          :columns="columns"
          :row-key="(record) => record.id"
          :loading="tableLoading"
          :data-source="tableData"
          :pagination="pageSet"
          :scroll="{ x: 1500, y: tableHeight }"
          :locale="{ filterConfirm: '确定', filterReset: '重置', emptyText: '暂无数据' }"
          @change="handleTableChange"
          bordered
        >
          <template #bodyCell="{ index, column, record }">
            <template v-if="column.key === 'index'">
              <div>{{ index + 1 }}</div>
            </template>
            <template v-if="column.key === 'operation'">
              <a-space>
                <a-button size="small" @click.stop="showModal('查看角色信息', CURDTYPE.查看, record as TableRowFeilds)">查看</a-button>
                <a-button type="primary" size="small" @click.stop="showModal('修改角色信息', CURDTYPE.修改, record as TableRowFeilds)">编辑</a-button>
                <a-popconfirm title="确定删除?" @confirm="onDelete(record as TableRowFeilds)">
                  <a-button danger size="small">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </section>
    <a-modal v-model:open="open" :width="800" :title="modalTitle" :maskClosable="false" centered destroyOnClose>
      <template #footer>
        <a-button key="back" @click="handleClose">关闭</a-button>
        <a-button key="submit" type="primary" v-if="crudType !== CURDTYPE.查看" :loading="confirmLoading" @click="handleOk">确定</a-button>
        <a-button key="reset" @click="resetFormState" v-if="crudType !== CURDTYPE.查看">重置</a-button>
      </template>
      <section class="modal-content-box">
        <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-item label="角色名称" name="name">
            <a-input v-model:value="formState.name" placeholder="角色名称" :disabled="disabledFormItem" :maxlength="50" show-count />
          </a-form-item>
          <a-form-item label="角色编码" name="code">
            <a-input v-model:value="formState.code" placeholder="角色编码" :disabled="disabledFormItem" :maxlength="255" show-count />
          </a-form-item>
          <a-form-item label="描述" name="description">
            <a-textarea v-model:value="formState.description" placeholder="描述" :disabled="disabledFormItem" :rows="4" :maxlength="255" show-count />
          </a-form-item>
        </a-form>
      </section>
    </a-modal>
  </section>
</template>

<script setup lang="ts">
import { RoleService } from '@/api'
import type { TableColumnsType, TableProps } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { FormState, Pagination, SearchForm, TableRowFeilds } from './types'
defineOptions({ name: 'Role' })
enum CURDTYPE {
  新增 = 1,
  修改 = 2,
  查看 = 3,
  删除 = 4,
}
// 分页器配置
const pageSet = ref<Pagination>({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ['10', '20', '30', '50', '100'],
  showQuickJumper: true,
  showTotal: (total: number) => {
    return `总数：${total} 条`
  },
})

// 搜素表单
const searchRormRef = ref()
const searchFormState = reactive<SearchForm>({
  name: '',
  code: '',
})
function onFinishSearch(values: SearchForm): void {
  console.log('Search-Params:', values)
  pageSet.value.current = 1
  getListData()
}
// 重置搜索表单
function resetSearchForm(): void {
  searchRormRef.value.resetFields()
  pageSet.value.current = 1
  getListData()
}
const disabledSeachBtn = computed(() => {
  return !(searchFormState.name || searchFormState.code)
})

const mainContentRef = ref<HTMLElement>()
const tableHeight = ref<number>(500)
const columns: TableColumnsType = [
  { title: '序号', width: 80, dataIndex: 'index', key: 'index', fixed: 'left', align: 'center' },
  { title: '角色名称', minWidth: 150, dataIndex: 'name', key: 'name', fixed: 'left', align: 'center' },
  { title: '角色编码', dataIndex: 'code', key: 'code', minWidth: 150, align: 'center' },
  { title: '描述', dataIndex: 'description', key: 'description', minWidth: 150, align: 'center' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', minWidth: 150, align: 'center' },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    align: 'center',
    width: 240,
  },
]
const tableLoading = ref<boolean>(false)
const tableData = ref<TableRowFeilds[]>([])

function handleTableChange(pag: { pageSize: number; current: number }, filters: any, sorter: any): TableProps['onChange'] {
  console.log('pag:==>', pag)
  console.log('filters:==>', filters)
  console.log('sorter:==>', sorter)
  pageSet.value = Object.assign(pageSet.value, pag)
  getListData()
  return
}

/** 新增、修改、查看、删除相关功能 */
const crudType = ref<number>(1)
const disabledFormItem = computed(() => {
  return crudType.value === CURDTYPE.查看
})
const formRef = ref()
const labelCol = { span: 5 }
const wrapperCol = { span: 17 }
const formState = ref<FormState>({
  name: '',
  code: '',
  description: '',
})
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'change' },
    { min: 2, max: 50, message: '最少两个字符，最长不超过50字符', trigger: 'blur' },
  ],
}
function resetFormState(): void {
  formRef.value.resetFields()
}
const modalTitle = ref<string>('')
const open = ref<boolean>(false)
const confirmLoading = ref<boolean>(false)
// 打开弹窗
function showModal(title: string, type: CURDTYPE, row?: TableRowFeilds): void {
  modalTitle.value = title
  crudType.value = type
  console.log('showModal row:==>', row)
  formState.value = { name: '', code: '', description: '' }
  if (type !== CURDTYPE.新增 && row) {
    Object.entries(row).forEach(([key, val]) => {
      /**@ts-ignore */
      formState.value[key] = val
    })
  }
  open.value = true
}

// 弹窗确定
function handleOk(): void {
  confirmLoading.value = true
  formRef.value
    .validate()
    .then(async () => {
      const data = toRaw(formState.value)
      console.log('values', data)
      const res = crudType.value === CURDTYPE.新增 ? await RoleService.add(data) : await RoleService.update(data.id + '', data)
      confirmLoading.value = false
      console.log('res:==>', res)
      if (res?.success) {
        window.$message.success(`${CURDTYPE[crudType.value]}角色成功！`)
        open.value = false
        getListData()
      } else {
        window.$message.error(`${CURDTYPE[crudType.value]}角色失败！` + res?.message)
      }
    })
    .catch((error: any) => {
      confirmLoading.value = false
      console.log('error', error)
    })
}

// 确定删除
async function onDelete(record: TableRowFeilds) {
  const row = toRaw(record)
  console.log('onDelete:==>', row)
  const res = await RoleService.remove(row?.id)
  if (res?.success) {
    window.$message.success('删除角色成功！')
    getListData()
    return true
  } else {
    window.$message.error('删除角色失败！' + res?.message)
    return false
  }
}

// 弹窗关闭后的回调
function handleClose() {
  confirmLoading.value = false
  open.value = false
}

// 获取列表数据
async function getListData() {
  tableLoading.value = true
  const params: RoleEntity.SearchParams = {
    page: pageSet.value.current,
    pageSize: pageSet.value.pageSize,
    name: searchFormState.name,
    code: searchFormState.code,
  }
  const res = await RoleService.page(params)
  console.log('getList：==>', res)
  if (res?.success) {
    const list = res?.data?.list || []
    tableData.value = list
    pageSet.value.total = res?.data?.total || 0
  } else {
    tableData.value = []
  }
  tableLoading.value = false
}

onMounted(() => {
  if (mainContentRef.value) {
    tableHeight.value = mainContentRef.value.offsetHeight - 64
  }
  getListData()
})
</script>

<style lang="scss" scoped>
.main-box {
  width: 100%;
  height: calc(100% - 76px);
  margin-top: 12px;

  .main-content {
    width: 100%;
    height: calc(100% - 52px);
  }
}
.modal-content-box {
  height: 400px;
  width: 100%;
}
</style>
